<template>
	<view class="conent">
		<view class="conent_box">
			<view class="from">
				<u--form labelPosition="top" :required="true" labelWidth="120" :model="addressInfo" :rules="rules"
					ref="uForm" :labelStyle="{'font-weight':'800'}">
					<u-form-item label="收货人" prop="name">
						<u-input v-model="addressInfo.name" placeholder="填写收货人姓名" />
					</u-form-item>
					<u-form-item label="手机号码" prop="phoneNumber">
						<u-input v-model="addressInfo.phoneNumber" type="number" placeholder="填写收货人联系电话" />
					</u-form-item>
					<u-form-item label="收货地址:" prop="address">
						<pick-regions style="width:100%;" @getRegion="handleGetRegion">
							<view v-if="addressInfo.address"
								style="padding: 10rpx 12rpx; border-radius: 10rpx;border:2rpx solid #f3f3f4; color: #000;font-size: 28rpx;">
								{{addressInfo.address}}
							</view>
							<view v-else
								style="padding: 10rpx 12rpx; border-radius: 10rpx;border:2rpx solid #f3f3f4; color: #c0c4cc;font-size: 28rpx;">
								请选择收货地区
							</view>
						</pick-regions>
					</u-form-item>
					<u-form-item label="详细地址" prop="detailAddress">
						<u-textarea v-model="addressInfo.detailAddress" placeholder="填写详细街道"></u-textarea>
					</u-form-item>
					<u-form-item labelPosition="left" labelWidth="80" label="默认地址:">
						<up-switch :activeValue="1" :inactiveValue="0" v-model="addressInfo.defaultFlag"
							activeColor="#07BFA5" @change="changeSwitch"></up-switch>
					</u-form-item>
				</u--form>
			</view>
			<u-button text="使用微信收货地址" color="#07BFA5"
				customStyle="width:90%;border-radius:16rpx;margin:auto;margin-top:40rpx;"
				@click="getAddressList"></u-button>
			<view class="read">
				<up-switch :activeValue="1" :inactiveValue="0" v-model="readBoole" activeColor="#07bfa5"
					@change="changeSwitchRead"></up-switch>
				<p>
					阅读并同意
					<text style="color:#0055ff" @click="getEvents('服务协议')">《服务协议》</text>
					与<text style="color:#0055ff" @click="getEvents('隐私政策')">《隐私政策》</text>
				</p>
			</view>
		</view>
		<u-button :text="navbarTitle" :icon="mode=='add'?'plus':'edit-pen'" iconColor="#fff" color="#07BFA5"
			customStyle="width:90%;border-radius:16rpx;position:fixed;left:5%; bottom:20rpx" @click="append"></u-button>
	</view>
</template>

<script setup>
	import pickRegions from './components/pick-regions/pick-regions.vue'
	import {
		ref,
		onMounted,
		watch
	} from 'vue'
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		list,
		add,
		update
	} from "@/api/pages/address.js"
	import router from '@/api/router';
	const navbarTitle = ref("添加地址")
	const mode = ref("add")
	const readBoole = ref(0)
	const userId = ref("")
	const uForm = ref(null)
	const addressInfo = ref({
		name: '收货人',
		phoneNumber: '13656322563',
		address: '',
		detailAddress: '地址地址地址',
		defaultFlag: 1
	})
	const rules = {
		name: [{
			type: 'string',
			required: true,
			message: '请填写姓名',
			trigger: ['blur', 'change']
		}],
		phoneNumber: [{
			type: 'string',
			required: true,
			message: '请填写联系电话',
			trigger: ['blur', 'change']
		}, {
			validator: (rule, value, callback) => {
				return uni.$u.test.mobile(value);
			},
			message: '手机号码不正确',
			trigger: ['change', 'blur'],
		}],
		address: [{
			type: 'string',
			required: true,
			message: '请选择地址',
			trigger: ['change', 'blur']
		}],
		detailAddress: [{
			type: 'string',
			required: true,
			message: '请填写详细地址',
			trigger: ['blur', 'change']
		}],
		defaultFlag: [{
			type: 'string',
			required: true,
			message: '请选择默认',
			trigger: ['blur', 'change']
		}]
	}
	onLoad((options) => {
		JSON.stringify(options) == "{}" ? navbarTitle.value = "添加地址" : navbarTitle.value = "修改地址"
		JSON.stringify(options) == "{}" ? mode.value = "add" : mode.value = "update"
		options.address ? addressInfo.value = JSON.parse(options.address) : addressInfo.value = {
			name: '',
			phoneNumber: '',
			address: '',
			detailAddress: '',
			defaultFlag: 0
		}
		console.log("123--", options, navbarTitle.value)
		uni.getStorage({
			key: 'account',
			success: (res) => {
				console.log("account", res.data)
				userId.value = res.data.id
			}
		})
	})
	const getAddressList = () => {
		wx.chooseAddress({
			success: (res) => {
				console.log("微信的收货地址", res);
				// this.addressInfo = res;
				addressInfo.value = {
					name: res.userName,
					phoneNumber: res.telNumber,
					address: res.provinceName+res.cityName+res.countyName,
					detailAddress: res.detailInfo,
					defaultFlag: 1
				}
			}
		})
	}
	const handleGetRegion = (region) => {
		console.log("选择城市", region[0].name + region[1].name + region[2].name);
		addressInfo.value.address = region[0].name + region[1].name + region[2].name
	}
	const changeSwitch = (e) => {
		addressInfo.value.defaultFlag = e
	}
	const changeSwitchRead = (e) => {
		console.log(e);
		readBoole.value = e
	}
	const getEvents = (title) => {
		router.navigateTo({
			url: '/pageA/events/detail?title=' + title
		})
	}
	const append = () => {
		if (readBoole.value == '0') {
			uni.showToast({
				title: '请先阅读并同意《服务协议》与《隐私政策》',
				icon: 'none',
			})
			return
		}
		console.log(uForm.value.validate());
		uForm.value.validate().then(valid => {
			if (valid) {
				if (mode.value == 'add') {
					addAddress({
						...addressInfo.value,
						userId: userId.value
					})
				} else {
					updateAddress({
						...addressInfo.value,
						userId: userId.value
					})
				}
				// uni.$u.toast('校验通过')
			} else {
				uni.$u.toast('校验失败')
			}
		}).catch(() => {
			// 处理验证错误  
			uni.$u.toast('校验失败')
		});
	}
	const addAddress = async (form) => {
		const res = await add(form).then(
			// console.log("完成")
			router.navigateBack(1)
		)
	}
	const updateAddress = async (form) => {
		const res = await update(form).then(
			// console.log("完成")
			router.navigateBack(1)
		)
	}
</script>

<style lang="scss" scoped>
	body {
		background: #F8F8F8;
	}

	.conent_box {
		margin: 10rpx;
		text-align: left;

		.from {
			border-radius: 20rpx;
			background: #fff;
			padding: 20rpx;
			box-shadow: 2px 2px 2px rgba(0, 0, 0, .3);
			border-radius: 20rpx;
		}

		.read {
			padding: 10rpx;
			display: flex;
			font-size: 32rpx;
			line-height: 54rpx;
		}
	}
</style>